<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
    protected $table = 'goods';
    
    protected $fillable = [
    	'name',
    	'category_id',
    	'brand_id',
    	'sub_title',
    	'cover_img',
    	'market_price',
    	'price',
    	'stock',
    	'is_new',
    	'is_hot',
    	'is_recommend',
    	'is_index',
    	'status',
    	'virtual_sales',
    	'description',
        'member_only',
    ];

    public function attrs()
    {
    	return $this->hasMany(Attr::class, 'goods_id');
    }

    public function pictures()
    {
    	return $this->hasMany(Picture::class);
    }

    public function comments() {
        return $this->hasMany(Comment::class, 'goods_id');
    }

    public function category()
    {
    	return $this->belongsTo(Category::class)->withDefault();
    }

    public function brand()
    {
    	return $this->belongsTo(Brand::class)->withDefault();
    }

    public function saveAttr($data)
    {
        $attrs = [];
    	$this->attrs()->delete();
    	if(!empty($data))
    	{
            $attrs = [];
            foreach($data as $k => $v)
            {
                $name = array_filter($v['name'], 'strlen');
                if(count($name) > 0 && $v['stock'])
                {
                    $v['name'] = implode(',', $name);
                    $attrs[$k] = $v;
                }
            }
            if(!empty($attrs))
            {
                $this->attrs()->createMany($attrs);
            }
    	}
    }

    public function savePictures($data)
    {
    	$this->pictures()->delete();
    	$data = array_filter($data);
    	if(!empty($data))
    	{
    		foreach($data as $v)
	    	{
	    		$res[]['path'] = $v;
	    	}
	    	return $this->pictures()->createMany($res);
    	}
    }

    public function scopeMemberGoods($query)
    {
        return $query->where('member_only', 1)->latest()->limit(4);
    }

    #商品搜索
    public function scopeFilter($query, $data) {
        if(empty($data) || !is_array($data)) {
            return $query;
        }

        $fields = ['name', 'category_id', 'brand_id', 'status'];
        foreach($data as $field => $v) {
            if(strlen($v)) {
                if(in_array($field, $fields)) {
                    if($field == 'name') {
                        $query->where('name', 'like', '%'.$v.'%');
                        continue;
                    }
                    $query->where($field, $v);
                }
            }
        }
        return $query;
    }
}
